/*
 * @(#)cn.design.pattern.interpreter 2020/4/27/0027
 *
 * Copy Right@ 人人译视界
 */


package cn.design.pattern.interpreter;

import sun.util.calendar.CalendarUtils;

import java.util.HashMap;
import java.util.Stack;

/**
 * <pre>
 * @author tuwei
 *
 * @version 0.9
 *
 * 修改版本: 0.9
 * 修改日期: 2020/4/27/0027
 * 修改人 :  tuwei
 * 修改说明: 初步完成
 * 复审人 ：
 * </pre>
 */
public class Calculator {
	private Expression expression;

	public Calculator(String expStr) {
		Stack<Expression> stack = new Stack<>();
		char[] charArray = expStr.toCharArray();

		Expression left = null;
		Expression right = null;
		for (int i = 0; i < charArray.length; i++) {
			switch (charArray[i]) {
				case '+':
					left = stack.pop();
					right = new VarExpression((String.valueOf(charArray[++i])));
					stack.push(new AddExpression(left, right));
					break;
				case '-':
					left = stack.pop();
					right = new VarExpression(String.valueOf(charArray[++i]));
					stack.push(new SubExpression(left, right));
					break;
				default:
					stack.push(new VarExpression(String.valueOf(charArray[i])));
					break;
			}
		}
		this.expression = stack.pop();
	}

	public int run(HashMap<String, Integer> var) {
		return this.expression.interpreter(var);
	}
}